package zhengqc.union_find;

public class UnionFindUsingQuickUnion implements UnionFind {
    private int[] parents;

    public UnionFindUsingQuickUnion(int size) {
        this.parents = new int[size];
        for (int i = 0; i < size; ++i) {
            parents[i] = i;
        }
    }
    private void rangeCheck(int index) {
        if (index < 0 || index >= parents.length) {
            throw new IllegalArgumentException(index + " is out of bound!");
        }
    }
    private int find(int p) {
        rangeCheck(p);
        while (p != parents[p]) {
            p = parents[p];
        }
        return p;
    }
    @Override
    public int getSize() {
        return parents.length;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElement(int p, int q) {
        int pRoot = find(p),
            qRoot = find(q);
        if (pRoot == qRoot) {
            return;
        }
        parents[pRoot] = qRoot;
    }
}
